﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;
using System.Web;

namespace LunwenYun.Portal.WebLogic
{
    public class FileDownLoad
    {
        public static void Down(string ReWriteUrl)
        {
            //string ReWriteUrl = regex.Replace(rawUrl, config.UrlMappings[i].MappedUrl);
            if (System.IO.File.Exists(ReWriteUrl))
            {
                string queryString = string.Empty;
                HttpContext context = HttpContext.Current;
                string serverPath = context.Server.MapPath(ReWriteUrl);
                FileInfo File = new FileInfo(serverPath);
                context.Response.Clear();
                context.Response.AddHeader("Content-Disposition", "filename=" + File.Name);
                context.Response.AddHeader("Content-Length", File.Length.ToString());

                string fileExtension = File.Extension;
                // 根据文件后缀指定文件的Mime类型
                switch (fileExtension)
                {
                    case ".mp3":
                        context.Response.ContentType = "audio/mpeg3";
                        break;
                    case ".mpeg":
                        context.Response.ContentType = "video/mpeg";
                        break;
                    case ".jpg":
                        context.Response.ContentType = "image/jpeg";
                        break;
                    case ".gif":
                        context.Response.ContentType = "image/gif";
                        break;
                    case ".png":
                        context.Response.ContentType = "image/png";
                        break;
                    case ".doc":
                        context.Response.ContentType = "application/msword";
                        break;
                    case ".docx":
                        context.Response.ContentType = "application/msword";
                        break;
                    case ".xls":
                        context.Response.ContentType = "application/vnd.ms-excel";
                        break;
                    case ".xlsx":
                        context.Response.ContentType = "application/vnd.ms-excel";
                        break;
                    case ".ppt":
                        context.Response.ContentType = "application/vnd.ms-powerpoint";
                        break;
                    case ".pptx":
                        context.Response.ContentType = "application/vnd.ms-powerpoint";
                        break;
                    case ".pdf":
                        context.Response.ContentType = "application/pdf";
                        break;
                    case ".txt":
                        context.Response.ContentType = "text/plain";
                        break;
                    default:
                        context.Response.ContentType = "application/octet-stream";
                        break;

                }
                context.Response.WriteFile(File.FullName);
                context.Response.End();
            }
            else
            {
                HttpContext.Current.Response.Redirect("~/DownError.aspx");
            }

        }
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="_Request">Page.Request</param>
        /// <param name="_Response">Page.Respone</param>
        /// <param name="_fullPath">相对路径</param>
        /// <param name="_speed">下载速度(单位b) 50 * 1024  (50kb/s)</param>
        /// <returns></returns>
        public static bool DownLoadFile(HttpRequest _Request, HttpResponse _Response, string _fullPath, string fileName="")
        {

            try
            {
                string basePath = HttpContext.Current.Server.MapPath(_fullPath);
                if (!System.IO.File.Exists(basePath))
                {
                    return false;
                }
                basePath = basePath.Replace("/", "\\");
                FileStream myFile = new FileStream(basePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                string _fileName = string.IsNullOrEmpty(fileName) ? basePath.Substring(basePath.LastIndexOf('\\') + 1) : fileName;
                BinaryReader br = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    double pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    //int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    if (startBytes != 0)
                    {
                        //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                    }
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            //Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return false;
                }
                finally
                {
                    br.Close();

                    myFile.Close();
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}
